import type { Env, ShareFileItem } from '../types';

const R2_BUCKET_NAME = 'one';
const UPLOAD_DIR = 'upload';


// 实现R2存储的文件保存函数
export async function saveShareFile(
  env: Env,
  file: File,
  description: string,
  userId: number,
  groupId: number,
  fingerprintId: string
): Promise<{
  success: boolean;
  data?: ShareFileItem;
  error?: string;
}> {
  try {
    // 生成唯一的文件名
    const originalFilename = decodeURIComponent(file.name);
    const timestamp = Date.now();
    const fileExtension = originalFilename.split('.').pop() ? `.${originalFilename.split('.').pop()}` : '';
    // 提取文件名（不含扩展名）
    const filenameWithoutExtension = originalFilename.replace(fileExtension, '');

    // 安全地获取文件名前6个字符，避免截断Unicode字符
    let shortFilename = '';
    let charCount = 0;
    for (let i = 0; i < filenameWithoutExtension.length && charCount < 6; i++) {
      // 检查当前字符是否为双字节字符
      const char = filenameWithoutExtension[i];
      shortFilename += char;
      // 对于中文字符等非ASCII字符，算作1个字符
      charCount++;
    }

    // 如果不足6个字符，则用'x'补齐
    shortFilename = shortFilename.padEnd(6, 'x');

    // 确定一级目录 (扩展名或_) 
    const extDir = fileExtension ? fileExtension.slice(1).toLowerCase() : '_';

    // 确定二级目录 (哈希值的前2个字符)
    const hashDir = shortFilename;

    // 添加今天的日期
    const today = new Date().toISOString().split('T')[0];
    // 构建完整目录路径
    const dirPath = [UPLOAD_DIR, today, extDir, hashDir].join('/');

    // 生成新的安全文件名
    const safeFilename = `${timestamp}-${originalFilename}`;
    const newFilePath = `${dirPath}/${safeFilename}`;

    // 上传文件到R2存储桶
    await env.R2.put(newFilePath, await file.arrayBuffer(), {
      httpMetadata: { contentType: file.type },
      customMetadata: {
        userId: userId.toString(),
        groupId: groupId.toString(),
        description: description
      }
    });

    // 生成R2访问URL (假设桶是公开的或使用预签名URL)
    // 实际应用中可能需要根据你的R2配置调整URL生成方式
    const r2Url = `https://${R2_BUCKET_NAME}.r2.cloudflarestorage.com/one/${newFilePath}`;

    const result = await env.DB.prepare(
      'INSERT INTO share_file (user_id, create_at, filename, save_filename, file_size, file_type, path, group_id) VALUES (?, datetime(\'now\'), ?, ?, ?, ?, ?, ?) RETURNING *'
    )
      .bind(userId, file.name, newFilePath, file.size, file.type, r2Url, groupId)
      .first<ShareFileItem>();

    return { success: true, data: result as any };
  } catch (error) {
    console.error('Error saving share file:', error);
    return { success: false, error: 'Failed to save file' };
  }
}

export async function getShareFileList(
  env: Env
): Promise<{
  success: boolean;
  data?: ShareFileItem[];
  error?: string;
}> {
  try {
    const result = await env.DB.prepare('SELECT * FROM share_file ORDER BY create_at DESC')
      .all<ShareFileItem>();

    return { success: true, data: result.results };
  } catch (error) {
    console.error('Error getting share file list:', error);
    return { success: false, error: 'Failed to get file list' };
  }
}

export async function deleteShareFile(
  env: Env,
  fileId: number
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await env.DB.prepare('DELETE FROM share_file WHERE id = ?')
      .bind(fileId)
      .run();

    return { success: true };
  } catch (error) {
    console.error('Error deleting share file:', error);
    return { success: false, error: 'Failed to delete file' };
  }
}


export async function getShareFile(
  env: Env,
  fileId: number
): Promise<{
  success: boolean;
  data?: ShareFileItem;
  error?: string;
}> {
  try {
    const result = await env.DB.prepare('SELECT * FROM share_file WHERE id = ?')
      .bind(fileId)
      .first<ShareFileItem>();

    // 从R2 获取文件
    // const file = await env.R2.get(result.save_filename);


    return { success: true, data: result as any };
  } catch (error) {
    console.error('Error getting share file:', error);
    return { success: false, error: 'Failed to get file' };
  }
}
